<template>
  <div class="screen-designer-page">
    <el-card class="designer-card">
      <!-- 顶部大屏信息栏 -->
      <div class="designer-header">
        <el-form :model="screenForm" inline>
          <el-form-item label="大屏名称">
            <el-input v-model="screenForm.name" placeholder="请输入名称" style="width:200px" />
          </el-form-item>
          <el-form-item label="分组">
            <el-select v-model="screenForm.group" placeholder="选择分组" style="width:120px">
              <el-option v-for="g in groupOptions" :key="g" :label="g" :value="g" />
            </el-select>
          </el-form-item>
          <el-form-item label="主题">
            <el-select v-model="screenForm.theme" style="width:110px">
              <el-option v-for="t in themeOptions" :key="t" :label="t" :value="t" />
            </el-select>
          </el-form-item>
           <el-form-item label="描述">
            <el-input v-model="screenForm.desc" placeholder="" style="width:200px" />
          </el-form-item>
        </el-form>
        <div style="margin-left:auto">
          <el-button size="small" @click="goBack">返回</el-button>
          <el-button type="primary" size="small" @click="saveScreen">保存大屏</el-button>
        </div>
      </div>

      <!-- 组件选择区与编辑画布 -->
      <div class="designer-main">
        <!-- 组件选择区 -->
        <el-card class="comp-bar" shadow="never">
          <div class="comp-title">组件库</div>
          <el-button v-for="c in compOptions" :key="c.type" type="primary" plain size="small" class="comp-btn"
            @click="addComp(c.type)">
            <i :class="c.icon" style="margin-right:4px"></i>{{ c.label }}
          </el-button>
        </el-card>

        <!-- 编辑画布区 -->
        <div class="screen-canvas" :style="canvasStyle">
          <div v-for="(comp, idx) in screenForm.comps" :key="comp.id" class="canvas-comp"
            :class="{ active: idx === activeIndex }" :style="getCompStyle(comp)" @mousedown="startDrag(idx, $event)"
            @click.stop="selectComp(idx)">
            <component
              :is="comp.type === 'chart' ? 'chart-demo' : comp.type === 'kpi' ? 'kpi-demo' : comp.type === 'text' ? 'text-demo' : 'map-demo'"
              v-bind="comp.props" />
            <div v-if="idx === activeIndex" class="resize-bar"></div>
          </div>
        </div>

        <!-- 属性编辑区 -->
        <el-card class="attr-bar" shadow="never">
          <div class="comp-title">属性面板</div>
          <template v-if="activeComp">
            <el-form :model="activeComp.props" label-width="60px" size="small">
              <!-- 图表组件属性 -->
              <template v-if="activeComp.type === 'chart'">
                <el-form-item label="标题">
                  <el-input v-model="activeComp.props.title" />
                </el-form-item>
                <el-form-item label="类型">
                  <el-select v-model="activeComp.props.chartType">
                    <el-option label="柱状图" value="bar" />
                    <el-option label="折线图" value="line" />
                    <el-option label="饼图" value="pie" />
                  </el-select>
                </el-form-item>
              </template>

              <!-- KPI 卡片属性 -->
              <template v-else-if="activeComp.type === 'kpi'">
                <el-form-item label="KPI名称">
                  <el-input v-model="activeComp.props.label" />
                </el-form-item>
                <el-form-item label="值">
                  <el-input v-model="activeComp.props.value" />
                </el-form-item>
              </template>

              <!-- 文本组件属性 -->
              <template v-else-if="activeComp.type === 'text'">
                <el-form-item label="内容">
                  <el-input v-model="activeComp.props.text" type="textarea" />
                </el-form-item>
                <el-form-item label="字号">
                  <el-input-number v-model="activeComp.props.fontSize" :min="12" :max="64" />
                </el-form-item>
              </template>

              <!-- 地图组件属性 -->
              <template v-else-if="activeComp.type === 'map'">
                <el-form-item label="地图类型">
                  <el-select v-model="activeComp.props.mapType">
                    <el-option label="中国" value="china" />
                    <el-option label="世界" value="world" />
                  </el-select>
                </el-form-item>
              </template>

              <!-- 通用宽度和高度设置 -->
              <el-form-item label="宽度">
                <el-input-number v-model="activeComp.width" :min="80" :max="700" />
              </el-form-item>
              <el-form-item label="高度">
                <el-input-number v-model="activeComp.height" :min="40" :max="500" />
              </el-form-item>
            </el-form>

            <!-- 删除组件 -->
            <div style="text-align:right">
              <el-button type="danger" size="small" @click="removeComp(activeIndex)">删除组件</el-button>
            </div>
          </template>

          <template v-else>
            <div style="color:#bbb;font-size:13px;">请选择组件进行编辑</div>
          </template>
        </el-card>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

// 组件库模拟
const compOptions = [
  { type: 'chart', label: '图表', icon: 'el-icon-data-analysis' },
  { type: 'kpi', label: 'KPI卡片', icon: 'el-icon-s-data' },
  { type: 'text', label: '文本', icon: 'el-icon-edit-outline' },
  { type: 'map', label: '地图', icon: 'el-icon-map-location' }
]

const groupOptions = ['生产', '能耗', '销售', '设备', '管理']
const themeOptions = ['深色', '浅色', '科技蓝', '简约白']

// 大屏表单数据
const screenForm = reactive({
  name: '',
  group: '',
  desc: '',
  theme: '深色',
  comps: []
})

const route = useRoute()
const router = useRouter()
const isEdit = computed(() => !!route.params.id)

// 激活组件（属性面板）
const activeIndex = ref(-1)
const activeComp = computed(() => screenForm.comps[activeIndex.value] || null)

// 新建/编辑初始化
onMounted(() => {
  if (isEdit.value) {
    const all = JSON.parse(localStorage.getItem('screens') || '[]')
    const current = all.find(s => s.id === Number(route.params.id))
    if (current) {
      screenForm.name = current.name
      screenForm.group = current.group
      screenForm.theme = current.theme
      screenForm.desc = current.desc
      screenForm.comps = current.comps?.map(c => ({ ...c, props: { ...c.props } })) || []
    }
  }
})

// 组件默认属性生成
function addComp(type) {
  const base = {
    id: Date.now() + Math.random(),
    type,
    x: 60 + Math.floor(Math.random() * 180),
    y: 60 + Math.floor(Math.random() * 120),
    width: 220,
    height: 140,
    props: {}
  }
  if (type === 'chart') {
    base.props = { title: '示例图表', chartType: 'bar' }
  } else if (type === 'kpi') {
    base.props = { label: 'KPI名称', value: 1000 }
    base.width = 130
    base.height = 70
  } else if (type === 'text') {
    base.props = { text: '请输入文本内容', fontSize: 20 }
    base.width = 160
    base.height = 50
  } else if (type === 'map') {
    base.props = { mapType: 'china' }
  }
  screenForm.comps.push(base)
  activeIndex.value = screenForm.comps.length - 1
}

function selectComp(idx) {
  activeIndex.value = idx
}
function removeComp(idx) {
  if (idx >= 0) {
    screenForm.comps.splice(idx, 1)
    activeIndex.value = -1
  }
}

// 拖拽移动
let dragState = { dragging: false, offsetX: 0, offsetY: 0 }
function startDrag(idx, e) {
  e.preventDefault()
  dragState = { dragging: true, offsetX: e.offsetX, offsetY: e.offsetY }
  document.onmousemove = (ev) => {
    if (!dragState.dragging) return
    const comp = screenForm.comps[idx]
    comp.x = Math.min(Math.max(0, ev.clientX - 320 - dragState.offsetX), 700 - comp.width)
    comp.y = Math.min(Math.max(0, ev.clientY - 130 - dragState.offsetY), 400 - comp.height)
  }
  document.onmouseup = () => {
    dragState.dragging = false
    document.onmousemove = null
    document.onmouseup = null
  }
}

// 样式
const canvasStyle = computed(() => ({
  width: '760px',
  height: '430px',
  background: screenForm.theme === '深色' ? '#181d2c' : screenForm.theme === '科技蓝' ? '#0a2a5e' : '#fff',
  borderRadius: '12px',
  position: 'relative',
  overflow: 'hidden',
  border: '2px solid #eee',
  margin: '0 20px'
}))

function getCompStyle(comp) {
  return {
    position: 'absolute',
    left: comp.x + 'px',
    top: comp.y + 'px',
    width: comp.width + 'px',
    height: comp.height + 'px',
    background: comp.type === 'text' ? '#fff' : 'rgba(255,255,255,0.07)',
    border: '2px solid ' + (comp.type === 'text' ? '#ccc' : '#6fa1ff'),
    borderRadius: '8px',
    cursor: 'move',
    boxShadow: '0 2px 8px 0 rgba(80,110,200,0.09)'
  }
}

// 保存大屏
function saveScreen() {
  if (!screenForm.name) return ElMessage.warning('请输入大屏名称')
  let all = JSON.parse(localStorage.getItem('screens') || '[]')
  if (isEdit.value) {
    const old = all.find(s => s.id === Number(route.params.id))
    all = all.map(s =>
      s.id === Number(route.params.id)
        ? { ...screenForm, id: Number(route.params.id), created: old?.created || new Date().toISOString().slice(0, 10) }
        : s
    )
  } else {
    all.unshift({
      ...screenForm,
      id: Date.now(),
      created: new Date().toISOString().slice(0, 10)
    })
  }
  localStorage.setItem('screens', JSON.stringify(all))
  ElMessage.success('大屏已保存！')
  goBack()
}

function goBack() {
  router.push({ name: 'ScreenList' })
}
</script>


<style scoped>
.screen-designer-page {
  padding: 24px;
  background: #f7f8fa;
}

.designer-card {
  max-width: 1260px;
  margin: 0 auto;
  border-radius: 14px;
}

.designer-header {
  display: flex;
  align-items: center;
  gap: 32px;
  margin-bottom: 10px;
}

.designer-main {
  display: flex;
  gap: 18px;
  min-height: 540px;
}

.comp-bar,
.attr-bar {
  flex: 0 0 155px;
  min-width: 240px;
  max-width: 330px;
  background: #fafbff;
}

.comp-title {
  font-size: 15px;
  color: #1e80ff;
  font-weight: 600;
  margin-bottom: 10px;
}

.comp-btn {
  margin-bottom: 8px;
  width: 100%;
}

.screen-canvas {
  flex: 1;
  position: relative;
  background: #fff;
  min-width: 600px;
  min-height: 380px;
  margin: 0 10px;
  border: 2px solid #eee;
  border-radius: 14px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.canvas-comp {
  position: absolute;
  box-sizing: border-box;
  transition: box-shadow .2s;
  z-index: 1;
}

.canvas-comp.active {
  box-shadow: 0 0 0 2px #1e80ff;
  z-index: 2;
}

.resize-bar {
  position: absolute;
  right: 4px;
  bottom: 4px;
  width: 16px;
  height: 16px;
  border-radius: 2px;
  background: #e1ecff;
  border: 1px solid #86b2fe;
  cursor: pointer;
}

.attr-bar {
  min-height: 380px;
}
</style>
